package com.niodata.md.rdb.crawler;

import com.niodata.md.rdb.model.DataBase;
import com.niodata.md.rdb.model.Table;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;

/**
 * retrieve table/view row count.
 */
public class RowCountRetrieval extends AbstractRetrieval {
  @Override
  public List<MetaDataRetrieval> retrieveMetaData() throws Exception {
    DataBase dataBase = this.getCatalog().getDataBase(
        ArrayUtils.subarray(this.getParentPath(), 0, 2));
    Table table = getCatalog().getTable(
        ArrayUtils.subarray(this.getParentPath(), 0, 3));
    Connection connection = this.getDataSourceInfo().getConnection(dataBase.getName(), table.getSchema());
    try {
      Statement statement = connection.createStatement();
      String tableQualifier = "";
      String schema = table.getSchema();
      if (schema != null && schema.length() > 0) {
        tableQualifier =  dataBase.getName() + "."  + schema + "." + table.getName();
      } else {
        tableQualifier =  dataBase.getName() + "." + table.getName();
      }
      String sql = "SELECT COUNT(*) FROM " + tableQualifier;
      ResultSet rs = statement.executeQuery(sql);
      rs.next();
      int count = rs.getInt(1);
      table.setRowCount(count);
    } finally {
      connection.close();
    }
    return Collections.emptyList();
  }
}
